package com.lwtek.demo;

import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;

import androidx.appcompat.app.AppCompatActivity;

import com.lwtek.demo.databinding.ActivityStorageBinding;

public class StorageActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    private ActivityStorageBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStorageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        getInfo();
    }

    private void initView() {
        binding.storeMode.setOnCheckedChangeListener(this);
        binding.updateBtn.setOnClickListener(this);
        binding.uploadDataBtn.setOnClickListener(this);
        binding.clearStoreDataBtn.setOnClickListener(this);
    }

    private void getInfo() {
        MyApplication.getDevice().getStoreMode((data, error) -> {
            if (data != null) runOnUiThread(() -> binding.storeMode.setChecked(data));
        });
        MyApplication.getDevice().getStoreTotal((data, error) -> {
            if (data != null) runOnUiThread(() -> binding.totalView.setText(data.toString()));
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int vid = buttonView.getId();
        if (vid == binding.storeMode.getId()) {
            MyApplication.getDevice().setStoreMode(isChecked);
        }
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == binding.updateBtn.getId()) {
            MyApplication.getDevice().getStoreTotal((data, error) -> {
                if (data != null) runOnUiThread(() -> binding.totalView.setText(data.toString()));
            });
        } else if (vid == binding.uploadDataBtn.getId()) {
            MyApplication.getDevice().getStoreData((data, error) -> {
                if (data != null) runOnUiThread(() -> binding.textView.setText(data));
            });
        } else if (vid == binding.clearStoreDataBtn.getId()) {
            MyApplication.getDevice().clearStoreData();
        }
    }
}